package com.zhou.copyjar;

import java.io.*;
import java.util.*;
import java.util.jar.*;

public class ManifestDependencyParser {


    /**
     * 解析 JAR 文件的 MANIFEST.MF 并获取 Class-Path 声明的依赖
     *
     * @param jarPath JAR 文件路径
     * @return 依赖的 JAR 包集合
     */
    public static Set<String> parseManifestDependencies(File jarPath) throws IOException {
        Set<String> dependencies = new HashSet<>();
        
        try (JarFile jarFile = new JarFile(jarPath)) {
            // 获取主清单文件
            Manifest manifest = jarFile.getManifest();
            if (manifest == null) return dependencies;

            // 获取 Class-Path 属性
            Attributes mainAttributes = manifest.getMainAttributes();
            String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH);
            
            if (classPath != null && !classPath.trim().isEmpty()) {
                // 分割多个依赖项（空格分隔）
                String[] jars = classPath.split("\\s+");
                
                for (String jar : jars) {
                    // 清理路径并添加
                    String cleanPath = jar.trim();
                    if (!cleanPath.isEmpty()) {
                        dependencies.add(cleanPath);
                    }
                }
            }
        }
        return dependencies;
    }
}